#!/bin/bash
#--------------------------------------------------
# This script is used for: 
# 1. to download and import smartide images
# @author:   jilibin
# @usage:    ./sedown
#--------------------------------------------------
version=v1.0.5
echo "version:$version"
set -o nounset
set -o errexit
#set -o xtrace

# deployment mode ：公有云模式cloud，私有部署private。区别在于公有云模式使用的是LoadBalancer，私有部署使用NodePort模式
deploymentMode=private

# default settings, can be overridden by cmd line options, see usage
DOCKER_VER=20.10.9

# Docker Registry
smartideDockerhub=registry.cn-hangzhou.aliyuncs.com
smartideDockerNamespace=smartide
smartideDockerURL=$smartideDockerhub/$smartideDockerNamespace
dockerRegistry=smartide.io.local:5000
dockerNamespace=smartide
dockerURL=$dockerRegistry/$dockerNamespace
dockerName=
dockerPwd=

# smartide tekton image
tektonPipelineVer=v0.32.0
tektonTriggersVer=v0.18.0
tektonDashboardVer=v0.23.0

# smartide server image
smartideServerVer=7273
smartideCliVer=7251

# smartide web config
webSSL=false   #false/true

# smartide server config
dbPassword=SmartIDE@123
apiHost=http://10.1.0.4:8000
tektonTriggerHost=http://10.1.0.4:8000/tekton-trigger
hybridDownloadUrl=http://20.195.44.31:6800/hybrid
templateGitUrl=https://gitee.com/smartide/smartide-templates.git
assetsUrl=http://20.195.44.31:6800/assets
oemEnable=false    #false/true
title=SmartIDE
docUrl=https://smartide.cn

# smartide marketplace
MARKETPLACE_DOMAIN=20.195.44.31
MARKETPLACE_DOMAIN_FULL=http://20.195.44.31:6800
MARKETPLACE_DATABASE=marketplace
MARKETPLACE_DATABASE_USERNAME=smartide
MARKETPLACE_DATABASE_PASSWORD=SmartIDE@123
MARKETPLACE_PGADMIN_USERNAME=smartide
MARKETPLACE_PGADMIN_PASSWORD=SmartIDE@123


function usage() {
  echo -e "\033[33mUsage:\033[0m sedown [options] [args]"
  cat <<EOF
  option:
    -D         download tekton && server images into "$BASE/down" or upload to docker local registry
    -B         build tekton && server manifest before deploy
    -K         deploy smartide tekton && server on k8s
    -R         run docker local registry
    -N         set smartide server by nodeport
    -A         download static assets(include hybrid resource) or deployment website with nginx
    -E         install docker && docker-compose
    -S         deploy vmlc feature(sysbox)
EOF
}

function logger() {
  TIMESTAMP=$(date +'%Y-%m-%d %H:%M:%S')
  case "$1" in
    debug)
      echo -e "$TIMESTAMP \033[36mDEBUG\033[0m $2"
      ;;
    info)
      echo -e "$TIMESTAMP \033[32mINFO\033[0m $2"
      ;;
    warn)
      echo -e "$TIMESTAMP \033[33mWARN\033[0m $2"
      ;;
    error)
      echo -e "$TIMESTAMP \033[31mERROR\033[0m $2"
      ;;
    *)
      ;;
  esac
}

function download_all() {
  mkdir -p "$BASE/down"
  get_smartide_sedown && \
  download_docker && \
  get_registry && \
  get_smartide_tekton_images && \
  get_smartide_server_images && \
  get_smartide_dev_images && \
  get_smartide_sysbox
  get_smartide_marketplace_images
  

  mkdir -p "$BASE/manifests"
  get_smartide_tekton_manifests && \
  get_smartide_server_manifests

  get_smartide_marketplace_files
}

function get_smartide_sedown() {
  logger info "download smartide sedown"
  if [[ ! -f "$BASE/sedown" ]];then
    wget -P "$BASE" \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/sedown
  else
    logger info "smartide sedown are already existed:"
  fi
}

function get_smartide_tekton_images() {
  logger info "download smartide tekton images, then upload to the local registry"

  # tekton-pipeline
  if [[ ! -f "$imageDir/tekton-pipeline_$tektonPipelineVer.tar" ]];then
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-controller:$tektonPipelineVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-entrypoint:$tektonPipelineVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-webhook:$tektonPipelineVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-kubeconfigwriter:$tektonPipelineVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-git-init:$tektonPipelineVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-nop:$tektonPipelineVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-imagedigestexporter:$tektonPipelineVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-pullrequest-init:$tektonPipelineVer" && \
    docker pull "$smartideDockerURL/cloudsdktool-cloud-sdk" && \
    docker pull "$smartideDockerURL/distroless-base" && \
    docker save -o "$imageDir/tekton-pipeline_$tektonPipelineVer.tar" \
      "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-controller:$tektonPipelineVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-entrypoint:$tektonPipelineVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-webhook:$tektonPipelineVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-kubeconfigwriter:$tektonPipelineVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-git-init:$tektonPipelineVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-nop:$tektonPipelineVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-imagedigestexporter:$tektonPipelineVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-pullrequest-init:$tektonPipelineVer" \
      "$smartideDockerURL/cloudsdktool-cloud-sdk" \
      "$smartideDockerURL/distroless-base"
  else
    docker load -i "$imageDir/tekton-pipeline_$tektonPipelineVer.tar"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-controller:$tektonPipelineVer" "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-controller:$tektonPipelineVer"
    docker push "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-controller:$tektonPipelineVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-entrypoint:$tektonPipelineVer" "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-entrypoint:$tektonPipelineVer"
    docker push "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-entrypoint:$tektonPipelineVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-webhook:$tektonPipelineVer" "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-webhook:$tektonPipelineVer"
    docker push "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-webhook:$tektonPipelineVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-kubeconfigwriter:$tektonPipelineVer" "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-kubeconfigwriter:$tektonPipelineVer"
    docker push "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-kubeconfigwriter:$tektonPipelineVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-git-init:$tektonPipelineVer" "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-git-init:$tektonPipelineVer"
    docker push "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-git-init:$tektonPipelineVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-nop:$tektonPipelineVer" "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-nop:$tektonPipelineVer"
    docker push "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-nop:$tektonPipelineVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-imagedigestexporter:$tektonPipelineVer" "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-imagedigestexporter:$tektonPipelineVer"
    docker push "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-imagedigestexporter:$tektonPipelineVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-pipeline-cmd-pullrequest-init:$tektonPipelineVer" "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-pullrequest-init:$tektonPipelineVer"
    docker push "$dockerURL/tekton-releases-tektoncd-pipeline-cmd-pullrequest-init:$tektonPipelineVer"
    docker tag "$smartideDockerURL/cloudsdktool-cloud-sdk" "$dockerURL/cloudsdktool-cloud-sdk"
    docker push "$dockerURL/cloudsdktool-cloud-sdk"
    docker tag "$smartideDockerURL/distroless-base" "$dockerURL/distroless-base"
    docker push "$dockerURL/distroless-base"
  fi

  # tekton-triggers
  if [[ ! -f "$imageDir/tekton-triggers_$tektonTriggersVer.tar" ]];then
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-controller:$tektonTriggersVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-eventlistenersink:$tektonTriggersVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-interceptors:$tektonTriggersVer" && \
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-webhook:$tektonTriggersVer" && \
    docker save -o "$imageDir/tekton-triggers_$tektonTriggersVer.tar" \
      "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-controller:$tektonTriggersVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-eventlistenersink:$tektonTriggersVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-interceptors:$tektonTriggersVer" \
      "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-webhook:$tektonTriggersVer"
  else
    docker load -i "$imageDir/tekton-triggers_$tektonTriggersVer.tar"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-controller:$tektonTriggersVer" "$dockerURL/tekton-releases-tektoncd-triggers-cmd-controller:$tektonTriggersVer"
    docker push "$dockerURL/tekton-releases-tektoncd-triggers-cmd-controller:$tektonTriggersVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-eventlistenersink:$tektonTriggersVer" "$dockerURL/tekton-releases-tektoncd-triggers-cmd-eventlistenersink:$tektonTriggersVer"
    docker push "$dockerURL/tekton-releases-tektoncd-triggers-cmd-eventlistenersink:$tektonTriggersVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-interceptors:$tektonTriggersVer" "$dockerURL/tekton-releases-tektoncd-triggers-cmd-interceptors:$tektonTriggersVer"
    docker push "$dockerURL/tekton-releases-tektoncd-triggers-cmd-interceptors:$tektonTriggersVer"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-triggers-cmd-webhook:$tektonTriggersVer" "$dockerURL/tekton-releases-tektoncd-triggers-cmd-webhook:$tektonTriggersVer"
    docker push "$dockerURL/tekton-releases-tektoncd-triggers-cmd-webhook:$tektonTriggersVer"
  fi


  # tekton-dashboard
  if [[ ! -f "$imageDir/tekton-dashboard_$tektonDashboardVer.tar" ]];then
    docker pull "$smartideDockerURL/tekton-releases-tektoncd-dashboard-cmd-dashboard:$tektonDashboardVer" && \
    docker save -o "$imageDir/tekton-dashboard_$tektonDashboardVer.tar" \
      "$smartideDockerURL/tekton-releases-tektoncd-dashboard-cmd-dashboard:$tektonDashboardVer"
  else
    docker load -i "$imageDir/tekton-dashboard_$tektonDashboardVer.tar"
    docker tag "$smartideDockerURL/tekton-releases-tektoncd-dashboard-cmd-dashboard:$tektonDashboardVer" "$dockerURL/tekton-releases-tektoncd-dashboard-cmd-dashboard:$tektonDashboardVer"
    docker push "$dockerURL/tekton-releases-tektoncd-dashboard-cmd-dashboard:$tektonDashboardVer"
  fi

}

function get_smartide_server_images() {
  mkdir -p "$BASE/down"
  # server
  logger info "download smartide server images, then upload to the local registry"
  if [[ ! -f "$imageDir/smartide-server_$smartideServerVer.tar" ]];then
    docker pull "$smartideDockerURL/smartide-api:$smartideServerVer" && \
    docker pull "$smartideDockerURL/smartide-web:$smartideServerVer" && \
    docker save -o "$imageDir/smartide-server_$smartideServerVer.tar" \
      "$smartideDockerURL/smartide-api:$smartideServerVer" \
      "$smartideDockerURL/smartide-web:$smartideServerVer"
  else
    docker load -i "$imageDir/smartide-server_$smartideServerVer.tar"
    docker tag "$smartideDockerURL/smartide-api:$smartideServerVer" "$dockerURL/smartide-api:$smartideServerVer"
    docker push "$dockerURL/smartide-api:$smartideServerVer"
    docker tag "$smartideDockerURL/smartide-web:$smartideServerVer" "$dockerURL/smartide-web:$smartideServerVer"
    docker push "$dockerURL/smartide-web:$smartideServerVer"
  fi

  # cli
  logger info "download smartide server images, then upload to the local registry"
  if [[ ! -f "$imageDir/smartide-cli_$smartideCliVer.tar" ]];then
    docker pull "$smartideDockerURL/smartide-cli:$smartideCliVer" && \
    docker save -o "$imageDir/smartide-cli_$smartideCliVer.tar" \
      "$smartideDockerURL/smartide-cli:$smartideCliVer"
  else
    docker tag "$smartideDockerURL/smartide-cli:$smartideCliVer" "$dockerURL/smartide-cli:$smartideCliVer"
    docker push "$dockerURL/smartide-cli:$smartideCliVer"
  fi

  
  # server dependencies: phpmyadmin，mysql，busybox，redis
  logger info "download smartide server dependencies images, then upload to the local registry"
  if [[ ! -f "$imageDir/smartide-server-dependencies.tar" ]];then
    docker pull "$smartideDockerURL/phpmyadmin:5.1.1" && \
    docker pull "$smartideDockerURL/mysql:8.0.29" && \
    docker pull "$smartideDockerURL/busybox:1.29.3" && \
    docker pull "$smartideDockerURL/redis:6.0.16" && \
    docker save -o "$imageDir/smartide-server-dependencies.tar" \
      "$smartideDockerURL/phpmyadmin:5.1.1" \
      "$smartideDockerURL/mysql:8.0.29" \
      "$smartideDockerURL/busybox:1.29.3" \
      "$smartideDockerURL/redis:6.0.16"
  else
    docker load -i "$imageDir/smartide-server-dependencies.tar"
    docker tag "$smartideDockerURL/phpmyadmin:5.1.1" "$dockerURL/phpmyadmin:5.1.1"
    docker push "$dockerURL/phpmyadmin:5.1.1"
    docker tag "$smartideDockerURL/mysql:8.0.29" "$dockerURL/mysql:8.0.29"
    docker push "$dockerURL/mysql:8.0.29"
    docker tag "$smartideDockerURL/busybox:1.29.3" "$dockerURL/busybox:1.29.3"
    docker push "$dockerURL/busybox:1.29.3"
    docker tag "$smartideDockerURL/redis:6.0.16" "$dockerURL/redis:6.0.16"
    docker push "$dockerURL/redis:6.0.16"
  fi

  # server ingress
  logger info "download smartide server ingress images, then upload to the local registry"
  if [[ ! -f "$imageDir/smartide-server-ingress.tar" ]];then
    docker pull "$smartideDockerURL/kube-webhook-certgen:v1.1.1" && \
    docker pull "$smartideDockerURL/ingress-nginx-controller:v1.2.0" && \
    docker save -o "$imageDir/smartide-server-ingress.tar" \
      "$smartideDockerURL/kube-webhook-certgen:v1.1.1" \
      "$smartideDockerURL/ingress-nginx-controller:v1.2.0"
  else
    docker load -i "$imageDir/smartide-server-ingress.tar"
    docker tag "$smartideDockerURL/kube-webhook-certgen:v1.1.1" "$dockerURL/kube-webhook-certgen:v1.1.1"
    docker push "$dockerURL/kube-webhook-certgen:v1.1.1"
    docker tag "$smartideDockerURL/ingress-nginx-controller:v1.2.0" "$dockerURL/ingress-nginx-controller:v1.2.0"
    docker push "$dockerURL/ingress-nginx-controller:v1.2.0"
  fi
}

function get_smartide_dev_images() {
  if [[ ! -d "$imageDir/dev-images" ]];then
    logger info "download smartide dev images"
    mkdir -p "$imageDir/dev-images"
    wget -P $imageDir/dev-images/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/dev-images-list.txt
    while read image_url; do
      docker pull $image_url
      image_name=$(cut -d/ -f3 <<< $image_url)
      tar_file=$(sed 's/:/_/' <<< "$image_name").tar
      logger info "saving $imageDir/dev-images/$tar_file"
      docker save -o $imageDir/dev-images/$tar_file $image_url
    done < $imageDir/dev-images/dev-images-list.txt
  else
    logger info "loading smartide dev images"
    while read tar_file; do
      docker load -i "$tar_file"
    done < <(find $imageDir/dev-images -name "*.tar")

    while read image_url; do
      image_name=$(cut -d/ -f3 <<< $image_url)
      docker tag $image_url $dockerURL/"$image_name"
      docker push $dockerURL/"$image_name"
    done < $imageDir/dev-images/dev-images-list.txt
  fi
}

function get_smartide_sysbox() {
  logger info "download smartide sysbox images"
  if [[ ! -f "$imageDir/smartide-sysbox.tar" ]];then
    docker pull "$smartideDockerURL/sysbox-deploy-k8s:v0.5.2" && \
    docker save -o "$imageDir/smartide-sysbox.tar" "$smartideDockerURL/sysbox-deploy-k8s:v0.5.2"
  else
    docker load -i "$imageDir/smartide-sysbox.tar"
    docker tag "$smartideDockerURL/sysbox-deploy-k8s:v0.5.2" "$dockerURL/sysbox-deploy-k8s:v0.5.2"
    docker push "$dockerURL/sysbox-deploy-k8s:v0.5.2"
  fi 
}

function get_smartide_marketplace_images() {
  mkdir -p "$imageDir/marketplace"

  logger info "download smartide marketplace images"
  if [[ ! -f "$imageDir/marketplace/smartide-marketplace.tar" ]];then
    docker pull "$smartideDockerURL/postgres:12.2" && \
    docker pull "$smartideDockerURL/elasticsearch:7.4.0" && \
    docker pull "$smartideDockerURL/pgadmin4:4.18" && \
    docker pull "$smartideDockerURL/smartide-openvsx:v1.0" && \
    docker pull "$smartideDockerURL/nginx:latest" && \
    docker save -o "$imageDir/marketplace/smartide-marketplace.tar" \
      "$smartideDockerURL/postgres:12.2" \
      "$smartideDockerURL/elasticsearch:7.4.0" \
      "$smartideDockerURL/pgadmin4:4.18" \
      "$smartideDockerURL/smartide-openvsx:v1.0" \
      "$smartideDockerURL/nginx:latest"
  else
    docker load -i "$imageDir/marketplace/smartide-marketplace.tar"
  fi
}

function get_smartide_tekton_manifests() {
  logger info "download smartide tekton manifests"
  if [[ ! -d "$BASE/manifests/smartide-tekton-deployment" ]];then
    mkdir -p "$BASE/manifests/smartide-tekton-deployment"
    tektonManifestsPath="$BASE/manifests/smartide-tekton-deployment"
    wget -P $tektonManifestsPath/pipeline/v0.32.0 \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/pipeline/v0.32.0/smartide-tekton-release.yaml
    wget -P $tektonManifestsPath/dashboard/v0.32.0 \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/dashboard/v0.32.0/smartide-tekton-dashboard-release.yaml
    wget -P $tektonManifestsPath/trigger/v0.18.0 \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/trigger/v0.18.0/smartide-release.yaml
    wget -P $tektonManifestsPath/trigger/v0.18.0 \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/trigger/v0.18.0/smartide-interceptor.yaml
    wget -P $tektonManifestsPath/smartide-pipeline/aliyun \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/smartide-pipeline/aliyun/trigger.yaml
    wget -P $tektonManifestsPath/smartide-pipeline/aliyun \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/smartide-pipeline/aliyun/trigger-template.yaml
    wget -P $tektonManifestsPath/smartide-pipeline/aliyun \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/smartide-pipeline/aliyun/trigger-binding.yaml
    wget -P $tektonManifestsPath/smartide-pipeline/aliyun \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/smartide-pipeline/aliyun/trigger-event-listener.yaml
    wget -P $tektonManifestsPath/smartide-pipeline/aliyun \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/smartide-pipeline/aliyun/task-smartide-cli-release.yaml
    sed -i "s/{smartideCliVer}/$smartideCliVer/g" $tektonManifestsPath/smartide-pipeline/aliyun/task-smartide-cli-release.yaml
    wget -P $tektonManifestsPath/smartide-pipeline/aliyun \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/smartide-pipeline/aliyun/pipeline-smartide-cli.yaml
    wget -P $tektonManifestsPath \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-tekton-deployment/smartide-tekton-deployment.sh
  else
    logger warn "smartide tekton manifests are already existed: [$BASE/manifests/smartide-tekton-deployment]"
  fi
}

function get_smartide_server_manifests() {
  logger info "download smartide server manifests"
  if [[ ! -d "$BASE/manifests/smartide-server-deployment" ]];then
    mkdir -p "$BASE/manifests/smartide-server-deployment/k8s"
    serverManifestsPath="$BASE/manifests/smartide-server-deployment"
    wget -P $serverManifestsPath/k8s/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/k8s/gva-server-configmap.yaml
    wget -P $serverManifestsPath/k8s/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/k8s/gva-server-deployment.yaml
    sed -i "s/{smartideServerVer}/$smartideServerVer/g" $serverManifestsPath/k8s/gva-server-deployment.yaml
    wget -P $serverManifestsPath/k8s/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/k8s/gva-web-configmap.yaml
    wget -P $serverManifestsPath/k8s/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/k8s/gva-web-deploymemt.yaml
    sed -i "s/{smartideServerVer}/$smartideServerVer/g" $serverManifestsPath/k8s/gva-web-deploymemt.yaml
    wget -P $serverManifestsPath/k8s/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/k8s/myadmin-deployment.yaml
    wget -P $serverManifestsPath/k8s/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/k8s/mysql-deployment.yaml
    wget -P $serverManifestsPath/k8s/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/k8s/redis-deployment.yaml
    wget -P $serverManifestsPath \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/smartide-server-deployment.sh
    # server ingress
    mkdir -p "$BASE/manifests/smartide-server-deployment/ingress-controller"
    wget -P $serverManifestsPath/ingress-controller/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/ingress-controller/ingress-controller.yaml
    # server sysbox
    mkdir -p "$BASE/manifests/smartide-server-deployment/sysbox"
    wget -P $serverManifestsPath/sysbox/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/smartide-server-deployment/sysbox/sysbox-install.yaml  
  else
    logger warn "smartide server manifests are already existed: [$BASE/manifests/smartide-server-deployment]"
  fi
}

function get_smartide_marketplace_files() {
  logger info "download smartide marketplace files"
  if [[ ! -d "$BASE/marketplace" ]];then
    wget -P $BASE/marketplace/openvsx/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/2-SmartIDE_Marketplace/openvsx/docker-compose.yaml
    wget -P $BASE/marketplace/openvsx/configurations/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/2-SmartIDE_Marketplace/openvsx/configurations/application.yml
    wget -P $BASE/marketplace/openvsx/nginx/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/2-SmartIDE_Marketplace/openvsx/nginx/nginx.conf
  else
    logger warn "smartide marketplace files is already existed: [$BASE/marketplace]"
  fi
}

function start_smartide_marketplace() {
  logger info "start smartide marketplace"
  if [[ ! -d "$BASE/marketplace" ]];then
    logger error "smartide marketplace files is not existed."
  else
    cp -rf $BASE/marketplace/openvsx ~/

    sed -i "s|\#{DATABASE}\#|${MARKETPLACE_DATABASE}|g" ~/openvsx/configurations/application.yml
    sed -i "s|\#{DATABASE_USERNAME}\#|${MARKETPLACE_DATABASE_USERNAME}|g" ~/openvsx/configurations/application.yml
    sed -i "s|\#{DATABASE_PASSWORD}\#|${MARKETPLACE_DATABASE_PASSWORD}|g" ~/openvsx/configurations/application.yml
    sed -i "s|\#{DOMAIN}\#|${MARKETPLACE_DOMAIN_FULL}|g" ~/openvsx/configurations/application.yml

    sed -i "s|\#{DOMAIN}\#|${MARKETPLACE_DOMAIN}|g" ~/openvsx/nginx/nginx.conf

    sed -i "s|\#{Docker-Registry}\#|${smartideDockerURL}|g" ~/openvsx/docker-compose.yaml
    sed -i "s|\#{DATABASE}\#|${MARKETPLACE_DATABASE}|g" ~/openvsx/docker-compose.yaml
    sed -i "s|\#{DATABASE_USERNAME}\#|${MARKETPLACE_DATABASE_USERNAME}|g" ~/openvsx/docker-compose.yaml
    sed -i "s|\#{DATABASE_PASSWORD}\#|${MARKETPLACE_DATABASE_PASSWORD}|g" ~/openvsx/docker-compose.yaml
    sed -i "s|\#{PGADMIN_USERNAME}\#|${MARKETPLACE_PGADMIN_USERNAME}|g" ~/openvsx/docker-compose.yaml
    sed -i "s|\#{PGADMIN_PASSWORD}\#|${MARKETPLACE_PGADMIN_USERNAME}|g" ~/openvsx/docker-compose.yaml
    sed -i "s|8080:8080|6100:8080|g" ~/openvsx/docker-compose.yaml
    sed -i "s|8090:80|6090:80|g" ~/openvsx/docker-compose.yaml
    sed -i "s|80:80|6080:80|g" ~/openvsx/docker-compose.yaml
    sed -i "s|443:443|6443:443|g" ~/openvsx/docker-compose.yaml

    cd ~/openvsx
    docker-compose -p openvsx down
    docker-compose -p openvsx up -d
  fi
}

function get_registry() {
  if [[ ! -d "$BASE/registry" ]];then
    mkdir -p "$BASE/registry"
    docker pull "registry:2" && \
    docker save -o "$BASE/registry/registry-2.tar" "registry:2"
    wget -P $BASE/registry/certs \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/3-SmartIDE_Install_Toolkit/registry/certs/smartide.io.local.crt
    wget -P $BASE/registry/certs \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/3-SmartIDE_Install_Toolkit/registry/certs/smartide.io.local.key
  else
    logger warn "$BASE/registry is already existed";
  fi
}

function start_local_registry() {
  docker ps -a --format="{{ .Names }}"|grep registry > /dev/null 2>&1 && \
  { logger warn "registry is already running"; return 0; }

  if [[ ! -d "$BASE/registry" ]];then
    logger warn "$BASE/registry is not existed";
  else
    logger info "start local registry ..."
    docker load -i "$BASE/registry/registry-2.tar" > /dev/null
    mkdir -p /opt/kube/registry
    docker run -d \
          --name registry \
          --network host \
          --restart always \
          --memory 512m \
          --memory-swap -1 \
          -v /opt/kube/registry:/var/lib/registry \
          # 自签名证书客户端无法获取，报证书错误
          # -v $BASE/registry/certs:/etc/cert.d \
          # -e REGISTRY_HTTP_TLS_CERTIFICATE=/etc/cert.d/smartide.io.local.crt \
          # -e REGISTRY_HTTP_TLS_KEY=/etc/cert.d/smartide.io.local.key \
          registry:2

    sed -i "/smartide.io.local/d" /etc/hosts
    echo "127.0.0.1 smartide.io.local" >> /etc/hosts
  fi
}

function build_all_manifests() {
  build_smartide_tekton_manifests && \
  build_smartide_server_manifests
}

function build_smartide_tekton_manifests() {
  logger info "build smartide tekton manifests"
  tektonManifestsPath="$BASE/manifests/smartide-tekton-deployment"
  ## 替换镜像地址
  if test ! -z "$(grep registry.cn-hangzhou.aliyuncs.com -rl $tektonManifestsPath)";then
    sed -i "s#registry.cn-hangzhou.aliyuncs.com/smartide#$dockerURL#g" `grep registry.cn-hangzhou.aliyuncs.com -rl $tektonManifestsPath`
  fi
}

function build_smartide_server_manifests() {
  logger info "build smartide server manifests"
  if [[ ! -d "$BASE/manifests/smartide-server-deployment" ]];then
    logger error "smartide server manifests are not existed"
  else
    serverManifestsPath="$BASE/manifests/smartide-server-deployment"
    ## 替换镜像地址
    if test ! -z "$(grep registry.cn-hangzhou.aliyuncs.com -rl $serverManifestsPath)";then
      sed -i "s#registry.cn-hangzhou.aliyuncs.com/smartide#$dockerURL#g" `grep registry.cn-hangzhou.aliyuncs.com -rl $serverManifestsPath`
    fi
    ## 替换参数 manifests/smartide-server-deployment/k8s/gva-server-configmap.yaml
    gvaServerConfigmap="$serverManifestsPath/k8s/gva-server-configmap.yaml"
    logger info "manifest: [$gvaServerConfigmap] building..."
    sed -i "s|\$(DBPassword)|${dbPassword}|g" $gvaServerConfigmap
    sed -i "s|^      api-host:.*$|      api-host: ${apiHost}|g" $gvaServerConfigmap
    sed -i "s|^      tekton-trigger-host:.*$|      tekton-trigger-host: ${tektonTriggerHost}|g" $gvaServerConfigmap
    sed -i "s|^      hybrid-download-url:.*$|      hybrid-download-url: ${hybridDownloadUrl}|g" $gvaServerConfigmap
    sed -i "s|^      template-git-url:.*$|      template-git-url: ${templateGitUrl}|g" $gvaServerConfigmap
    sed -i "s|^        assets-url:.*$|        assets-url: ${assetsUrl}|g" $gvaServerConfigmap
    sed -i "s|^        oemEnable:.*$|        oemEnable: ${oemEnable}|g" $gvaServerConfigmap
    sed -i "s|^        title:.*$|        title:: ${title}|g" $gvaServerConfigmap
    sed -i "s|^        doc-url:.*$|        doc-url: ${docUrl}|g" $gvaServerConfigmap
    sed -i "s|^        cliVersion:.*$|        cliVersion: ${smartideCliVer}|g" $gvaServerConfigmap
    ## 替换参数 manifests/smartide-server-deployment/k8s/gva-server-deployment.yaml
    gvaServerDeployment="$serverManifestsPath/k8s/gva-server-deployment.yaml"
    logger info "manifest: [$gvaServerDeployment] building..."      
    sed -i "s|\$(Build.BuildId)|${smartideServerVer}|g" $gvaServerDeployment
    ## 替换参数 manifests/smartide-server-deployment/k8s/gva-web-configmap.yaml
    if [ "$webSSL" != "true" ];then
      gvaWebConfigmap="$serverManifestsPath/k8s/gva-web-configmap.yaml"
      logger info "manifest: [$gvaWebConfigmap] building SSL..."
      sed -i "s|        listen 443 ssl|        #listen 443 ssl|g" $gvaWebConfigmap
      sed -i "s|        ssl_certificate_key|        #ssl_certificate_key|g" $gvaWebConfigmap
      sed -i "s|        ssl_certificate|        #ssl_certificate|g" $gvaWebConfigmap
    fi
    ## 替换参数 manifests/smartide-server-deployment/k8s/gva-web-deploymemt.yaml
    gvaWebDeployment="$serverManifestsPath/k8s/gva-web-deploymemt.yaml"
    logger info "manifest: [$gvaWebDeployment] building..."
    sed -i "s|  type: LoadBalancer|  type: NodePort|g" $gvaWebDeployment
    sed -i '/loadBalancerIP/ d' $gvaWebDeployment
    sed -i "/      targetPort: 8080/a\      nodePort: 8000" $gvaWebDeployment
    sed -i "/      targetPort: 443/a\      nodePort: 8443" $gvaWebDeployment
    sed -i "s|\$(Build.BuildId)|${smartideServerVer}|g" $gvaWebDeployment
    if [ "$webSSL" != "true" ];then
      logger info "manifest: [$gvaWebDeployment] building SSL..."
      sed -i "s|            - mountPath: /etc/nginx/ssl|#            - mountPath: /etc/nginx/ssl|g" $gvaWebDeployment
      sed -i "s|              name: secret-volume|#            name: secret-volume|g" $gvaWebDeployment
      sed -i "s|        - name: secret-volume|#        - name: secret-volume|g" $gvaWebDeployment
      sed -i "s|          secret:|#          secret:|g" $gvaWebDeployment
      sed -i "s|            secretName: nginxsecret|#            secretName: nginxsecret|g" $gvaWebDeployment
    fi
    ## 替换参数 manifests/smartide-server-deployment/k8s/myadmin-deployment.yaml
    myadminDeployment="$serverManifestsPath/k8s/myadmin-deployment.yaml"
    logger info "manifest: [$myadminDeployment] building..."
    sed -i "s|  type: LoadBalancer|  type: NodePort|g" $myadminDeployment
    sed -i '/loadBalancerIP/ d' $myadminDeployment
    ## 替换参数 manifests/smartide-server-deployment/k8s/mysql-deployment.yaml
    mysqlDeployment="$serverManifestsPath/k8s/mysql-deployment.yaml"
    logger info "manifest: [$mysqlDeployment] building..."
    sed -i "s|\$(DBPassword)|${dbPassword}|g" $mysqlDeployment
    sed -i "/    - ReadWriteOnce/a\  storageClassName: managed-nfs-storage" $mysqlDeployment
  fi
}

function deploy_all() {
  deploy_smartide_tekton && \
  deploy_smartide_server
}

function deploy_smartide_tekton() {
  logger info "deploy smartide tekton manifests"
  if [[ ! -d "$BASE/manifests/smartide-tekton-deployment" ]];then
    logger error "smartide tekton manifests are not existed"
  else
    tektonManifestsPath="$BASE/manifests/smartide-tekton-deployment"
    sed -i "s#easzlab.io.local:5000#$dockerRegistry#g" `grep easzlab.io.local:5000 -rl $tektonManifestsPath`
    kubectl apply -f $tektonManifestsPath/pipeline/v0.32.0/smartide-tekton-release.yaml
    kubectl apply -f $tektonManifestsPath/dashboard/v0.32.0/smartide-tekton-dashboard-release.yaml
    sleep 15
    kubectl apply -f $tektonManifestsPath/trigger/v0.18.0/smartide-release.yaml
    kubectl apply -f $tektonManifestsPath/trigger/v0.18.0/smartide-interceptor.yaml
    sleep 5
    kubectl apply -f $tektonManifestsPath/smartide-pipeline/aliyun/trigger.yaml
    kubectl apply -f $tektonManifestsPath/smartide-pipeline/aliyun/trigger-template.yaml
    kubectl apply -f $tektonManifestsPath/smartide-pipeline/aliyun/trigger-binding.yaml
    kubectl apply -f $tektonManifestsPath/smartide-pipeline/aliyun/trigger-event-listener.yaml
    sleep 5
    kubectl apply -f $tektonManifestsPath/smartide-pipeline/aliyun/task-smartide-cli-release.yaml
    kubectl apply -f $tektonManifestsPath/smartide-pipeline/aliyun/pipeline-smartide-cli.yaml
  fi
}

function deploy_smartide_server() {
  logger info "deploy smartide server manifests"
  if [[ ! -d "$BASE/manifests/smartide-server-deployment" ]];then
    logger error "smartide server manifests are not existed"
  else
    serverManifestsPath="$BASE/manifests/smartide-server-deployment"
    kubectl apply -f $serverManifestsPath/k8s/gva-server-configmap.yaml
    kubectl apply -f $serverManifestsPath/k8s/gva-server-deployment.yaml
    kubectl apply -f $serverManifestsPath/k8s/gva-web-configmap.yaml
    kubectl apply -f $serverManifestsPath/k8s/gva-web-deploymemt.yaml
    kubectl apply -f $serverManifestsPath/k8s/myadmin-deployment.yaml
    kubectl apply -f $serverManifestsPath/k8s/mysql-deployment.yaml
    kubectl apply -f $serverManifestsPath/k8s/redis-deployment.yaml
  fi
}

function deploy_smartide_sysbox() {
  logger info "deploy smartide sysbox manifests"
  if [[ ! -d "$BASE/manifests/smartide-server-deployment/sysbox" ]];then
    logger error "smartide sysbox manifests are not existed"
  else
    ## 获取node类型的节点，在节点上添加 sysbox-install=yes 的 label
    kubectl get nodes -l kubernetes.io/role=node -o jsonpath='{.items[*].metadata.name}' | tr ' ' '\n'| xargs -I {} kubectl label node {} sysbox-install=yes
    kubectl apply -f $BASE/manifests/smartide-server-deployment/sysbox/sysbox-install.yaml
  fi
}

function reset_nodeport() {
  logger info "set smartide server ingress-controller with nodeport"
  serverManifestsPath="$BASE/manifests/smartide-server-deployment"
  kubectl delete namespace smartide-ingress-nginx
  sleep 35
  kubectl apply -f $serverManifestsPath/ingress-controller/ingress-controller.yaml
  logger info "set smartide server ingress-controller with nodeport, done!"
}

function download_hybrid() {
  if [[ ! -d "$BASE/assets/hybrid" ]];then
    logger info "download smartide hybrid resource."
    mkdir -p "$BASE/assets/hybrid"
    wget -P $BASE/assets/hybrid/ \
      https://raw.githubusercontent.com/SmartIDE/smartide-server-install/master/1-SmartIDE_Server_K8S/hybrid-list.txt
    while read url; do
      wget -P $BASE/assets/hybrid/ $url
    done < $BASE/assets/hybrid/hybrid-list.txt
  else
    logger warn "smartide hybrid tar.gz is already existed."
  fi
}

function down_or_start_local_assets() {
  if [[ ! -d "$BASE/assets" ]];then
    mkdir -p "$BASE/assets/assets"
    docker pull "nginx:latest" && \
    docker save -o "$BASE/assets/nginx.tar" "nginx:latest"
    assets="assets"
    if [ "$oemEnable" == "true" ];then
      assets="oem"
    fi
    wget -P $BASE/assets/assets/ https://smartidedl.blob.core.chinacloudapi.cn/$assets/favicon.ico
    wget -P $BASE/assets/assets/ https://smartidedl.blob.core.chinacloudapi.cn/$assets/logo-small.png
    wget -P $BASE/assets/assets/ https://smartidedl.blob.core.chinacloudapi.cn/$assets/logo.png
    wget -P $BASE/assets/assets/ https://smartidedl.blob.core.chinacloudapi.cn/$assets/myAvatar.png
    download_hybrid
  else
    logger info "start local assets nginx website: assets & hybrid ..."
    docker load -i "$BASE/assets/nginx.tar" > /dev/null
    docker run -d \
      -p 8015:80 \
      --name assets-nginx \
      --restart always \
      --volume /etc/smartide/assets/hybrid:/usr/share/nginx/html/hybrid \
      --volume /etc/smartide/assets/assets:/usr/share/nginx/html/assets \
      nginx:latest
    logger info "start local assets nginx,the port is 8015..."
  fi
}

function download_docker() {
  DOCKER_URL="https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/static/stable/x86_64/docker-${DOCKER_VER}.tgz"
  DOCKERCOMPOSE_URL="https://smartidedl.blob.core.chinacloudapi.cn/docker/compose/releases/download/2.6.1/docker-compose-linux-x86_64"
  DOCKERCOMPOSE_ARM_URL="https://smartidedl.blob.core.chinacloudapi.cn/docker/compose/releases/download/2.6.1/docker-compose-linux-aarch64"

  if [[ -f "$BASE/down/docker-${DOCKER_VER}.tgz" ]];then
    logger warn "docker binaries already existed"
  else
    logger info "downloading docker binaries, version $DOCKER_VER"
    if [[ -e /usr/bin/wget ]];then
      wget -c --no-check-certificate "$DOCKER_URL" || { logger error "downloading docker failed"; exit 1; }
      wget -c --no-check-certificate "$DOCKERCOMPOSE_URL" || { logger error "downloading docker-compose failed"; exit 1; }
      wget -c --no-check-certificate "$DOCKERCOMPOSE_ARM_URL" || { logger error "downloading docker-compose failed"; exit 1; }
    else
      curl -k -C- -O --retry 3 "$DOCKER_URL" || { logger error "downloading docker-compose failed"; exit 1; }
      curl -k -C- -O --retry 3 "$DOCKERCOMPOSE_URL" || { logger error "downloading docker-compose failed"; exit 1; }
      curl -k -C- -O --retry 3 "$DOCKERCOMPOSE_ARM_URL" || { logger error "downloading docker-compose failed"; exit 1; }
    fi
    /bin/mv -f "./docker-$DOCKER_VER.tgz" "$BASE/down"
    /bin/mv -f "./docker-compose-linux-x86_64" "$BASE/down"
    /bin/mv -f "./docker-compose-linux-aarch64" "$BASE/down"
  fi
}

function install_docker_env() {
  install_docker && \
  install_dockercompose
}

function install_docker() {
  # check if a container runtime is already installed
  systemctl status docker|grep Active|grep -q running && { logger warn "docker is already running."; return 0; }

  tar zxf "$BASE/down/docker-$DOCKER_VER.tgz" -C "$BASE/down" && \
  /bin/cp -f "$BASE"/down/docker/* "$BASE/bin" && \
  /bin/mv -f "$BASE"/down/docker/* /opt/kube/bin && \
  ln -sf /opt/kube/bin/docker /bin/docker 

  logger debug "generate docker service file"
  cat > /etc/systemd/system/docker.service << EOF
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.io
[Service]
Environment="PATH=/opt/kube/bin:/bin:/sbin:/usr/bin:/usr/sbin"
ExecStart=/opt/kube/bin/dockerd
ExecStartPost=/sbin/iptables -P FORWARD ACCEPT
ExecReload=/bin/kill -s HUP \$MAINPID
Restart=on-failure
RestartSec=5
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
Delegate=yes
KillMode=process
[Install]
WantedBy=multi-user.target
EOF

  # configuration for dockerd
  mkdir -p /etc/docker
  DOCKER_VER_MAIN=$(echo "$DOCKER_VER"|cut -d. -f1)
  CGROUP_DRIVER="cgroupfs"
  ((DOCKER_VER_MAIN>=20)) && CGROUP_DRIVER="systemd"
  logger debug "generate docker config: /etc/docker/daemon.json"
  logger debug "prepare register mirror for $REGISTRY_MIRROR"
  cat > /etc/docker/daemon.json << EOF
{
  "exec-opts": ["native.cgroupdriver=$CGROUP_DRIVER"],
  "registry-mirrors": [
    "https://docker.mirrors.ustc.edu.cn",
    "http://hub-mirror.c.163.com"
  ],
  "max-concurrent-downloads": 10,
  "log-driver": "json-file",
  "log-level": "warn",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
    },
  "data-root": "/var/lib/docker"
}
EOF

  # docker proxy setting
  http_proxy=${http_proxy:-}
  HTTP_PROXY=${HTTP_PROXY:-$http_proxy}
  https_proxy=${https_proxy:-}
  HTTPS_PROXY=${HTTPS_PROXY:-$https_proxy}
  USE_PROXY=0
  CONFIG="[Service]\n"

  if [[ ! -z ${HTTP_PROXY} ]]; then
    USE_PROXY=1
    CONFIG=${CONFIG}"Environment=HTTP_PROXY=${HTTP_PROXY}\n"
  fi
  if [[ ! -z ${HTTPS_PROXY} ]]; then
    USE_PROXY=1
    CONFIG=${CONFIG}"Environment=HTTPS_PROXY=${HTTPS_PROXY}\n"
  fi
  if [[ ${USE_PROXY} == 1 ]]; then
    logger debug "generate docker service http proxy file"
    mkdir -p /etc/systemd/system/docker.service.d
    c=$(echo -e "$CONFIG")
    cat > /etc/systemd/system/docker.service.d/http-proxy.conf << EOF
${c}
EOF
  fi

  if [[ -e /etc/centos-release || -e /etc/redhat-release ]]; then
    logger debug "turn off selinux in CentOS/Redhat"
    getenforce|grep Disabled || setenforce 0
    sed -i 's/^SELINUX=.*$/SELINUX=disabled/g' /etc/selinux/config
  fi

  logger debug "enable and start docker"
  systemctl enable docker
  systemctl daemon-reload && systemctl restart docker && sleep 4
}

function install_dockercompose() {
  which docker-compose >/dev/null && { logger warn "docker-compose is already installed."; return 0; }
  arch=$(uname -m)
  if [ "$arch" == 'arm64' ];then 
    sudo cp $BASE/down/docker-compose-linux-aarch64 /usr/local/bin/docker-compose
  elif [ "$arch" == 'aarch64' ];then
    sudo cp $BASE/down/docker-compose-linux-aarch64 /usr/local/bin/docker-compose
  elif [ "$arch" == 'x86_64' ];then
    sudo cp $BASE/down/docker-compose-linux-x86_64 /usr/local/bin/docker-compose
  else
    sudo cp $BASE/down/docker-compose-linux-x86_64 /usr/local/bin/docker-compose
  fi
  sudo chmod +x /usr/local/bin/docker-compose
  docker-compose --version
}



### Main Lines ##################################################
function main() {
  BASE="/etc/smartide"
  imageDir="$BASE/down"

  # check if use bash shell
  readlink /proc/$$/exe|grep -q "bash" || { logger error "you should use bash shell, not sh"; exit 1; }
  # check if use with root
  [[ "$EUID" -ne 0 ]] && { logger error "you should run this script as root"; exit 1; }
  
  [[ "$#" -eq 0 ]] && { usage >&2; exit 1; }
  
  ACTION=""
  while getopts "DKBRNAEMS" OPTION; do
      case "$OPTION" in
        D)
          ACTION="download_all"
          ;;
        B)
          ACTION="build_all_manifests"
          ;;
        K)
          ACTION="deploy_all"
          ;;
        R)
          ACTION="start_local_registry"
          ;;
        N)
          ACTION="reset_nodeport"
          ;;
        A)
          ACTION="down_or_start_local_assets"
          ;;
        E)
          ACTION="install_docker_env"
          ;;
        M)
          ACTION="start_smartide_marketplace"
          ;;
        S)
          ACTION="deploy_smartide_sysbox"
          ;;
        ?)
          usage
          exit 1
          ;;
      esac
  done
  
  [[ "$ACTION" == "" ]] && { logger error "illegal option"; usage; exit 1; }
  
  # excute cmd "$ACTION" 
  logger info "Action begin: $ACTION"
  ${ACTION} || { logger error "Action failed: $ACTION"; return 1; }
  logger info "Action successed: $ACTION"
}

main "$@"
